﻿#include "widget.h"
#include "GL/gl.h"
#include <QDateTime>

#define BUFFER_OFFSET(offset) ((void*) (offset))

Widget::Widget()
    :m_counter(0.0)
{
    setWindowTitle(QStringLiteral("小课1-颜色过渡特效"));
    m_Timer = new QTimer(this);
    connect(m_Timer, &QTimer::timeout, this, &Widget::timeout);
    m_Timer->start(100);
}

Widget::~Widget()
{

}

void Widget::initializeGL()
{
    initializeOpenGLFunctions();

    m_program = new QOpenGLShaderProgram(this);

    //编译代码-添加顶点着色器
    m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/triangles.vert");
    //编译代码-添加片段着色器
    m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/triangles.frag");

    //链接着色器
    m_program->link();

    //VAO，VBO数据部分
    GLfloat vertices[] = {
        -1.0f, -1.0f, 0.0f, // left down
        1.0f, -1.0f, 0.0f, // right down
        1.0f,  1.0f, 0.0f,  // right up

        1.0f,  1.0f, 0.0f,  // right up
        -1.0f, 1.0f, 0.0f, // left up
        -1.0f, -1.0f, 0.0f, // left down

    };

    //得到顶点属性名在着色器参数列表中的位置-0
    m_posAttr = m_program->attributeLocation("aPos");

    glGenVertexArrays(1, m_VAO);
    glBindVertexArray(m_VAO[0]);

    glGenBuffers(1, m_VBO);
    glBindBuffer(GL_ARRAY_BUFFER, m_VBO[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    //链接顶点属性
    glVertexAttribPointer(m_posAttr, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), BUFFER_OFFSET(0));
    glEnableVertexAttribArray(m_posAttr);

    //解绑缓存着色器（绑定和解绑的顺序很重要，勿更改）
    glBindBuffer(GL_ARRAY_BUFFER, 0);


}

void Widget::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);
}

void Widget::paintGL()
{
//    qDebug()<<__FUNCTION__;
    glClearColor(0.2f, 0.3f, 0.3f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    m_program->bind();
    m_program->setUniformValue("Time", m_counter);
    glBindVertexArray(m_VAO[0]);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    m_program->release();
}

void Widget::timeout()
{
    m_counter+=0.1;
    update();
}
